package com.easy.controller;

import com.easy.bean.Borrow;
import com.easy.service.BorrowService;
import com.easy.util.Page;
import com.easy.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("borrow")
public class BorrowController {

    @Autowired
    private BorrowService borrowService;

    // 借书
    @PostMapping("/borrow")
    public Result borrow(@RequestParam("user_id") Integer user_id,
                         @RequestParam("book_id") Integer book_id) {
        try {
            Borrow borrow = borrowService.borrowBook(user_id, book_id);
            return Result.success("借书成功", borrow);
        } catch (Exception e) {
            return Result.fail(500, e.getMessage());
        }
    }

    // 还书
    @PostMapping("/return")
    public Result returnBook(@RequestParam("borrowId") Integer borrowId) {
        try {
            Borrow borrow = borrowService.returnBook(borrowId);
            return Result.success("还书成功", borrow);
        } catch (Exception e) {
            return Result.fail(500, e.getMessage());
        }
    }

    // 查询用户借阅记录
    @GetMapping("/user/{user_id}")
    public Result findByUser(@PathVariable("user_id") Integer user_id) {
        List<Borrow> borrows = borrowService.findByUser(user_id);
        return Result.success(borrows);
    }

    // 查询书籍借阅记录
    @GetMapping("/book/{book_id}")
    public Result findByBook(@PathVariable("book_id") Integer book_id) {
        List<Borrow> borrows = borrowService.findByBook(book_id);
        return Result.success(borrows);
    }

    // 查询用户未归还的书籍
    @GetMapping("/notreturn/{user_id}")
    public Result findNotReturnByUser(@PathVariable("user_id") Integer user_id) {
        List<Borrow> borrows = borrowService.findNotReturnByUser(user_id);
        return Result.success(borrows);
    }

    // 分页查询所有借阅记录
    @GetMapping("/page")
    public Result page(Page page, Borrow borrow) {
        borrowService.page(page, borrow);
        return Result.success(page);
    }
}